package com.yiyihealth.cherriesadmin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yiyihealth.cherriesadmin.core.http.HttpResult;
import com.yiyihealth.cherriesadmin.core.utils.AESUtils;
import com.yiyihealth.cherriesadmin.core.utils.JKTUtil;
import com.yiyihealth.cherriesadmin.core.web.BaseController;
import com.yiyihealth.cherriesadmin.model.*;
import com.yiyihealth.cherriesadmin.model.jkt.*;
import com.yiyihealth.cherriesadmin.model.wrapper.PubHospitalWrapper;
import com.yiyihealth.cherriesadmin.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.yiyihealth.cherriesadmin.core.utils.JKTUtil.sortMap;

/**
 * 医疗机构信息表(PubHospital)表控制层
 *
 * @author chen
 * @since 2020-09-14 20:03:50
 */
@Slf4j
@Api(tags = "医院管理")
@RestController
@RequestMapping("hospital")
public class PubHospitalController extends BaseController<PubHospital, PubHospitalWrapper, Long> {
    /**
     * 服务对象
     */
    @Resource
    private OrdAppointmentService ordAppointmentService;
    @Resource
    private PubSuffererService suffererService;
    @Resource
    private PubHospitalService hospitalService;
    @Resource
    private PubPatientsService pubPatientsService;
    @Resource
    private OrdSourceDetailService sourceDetailService;
    @Resource
    private JktFunc10006 jktFunc10006;
    @Resource
    private JThealth jThealth;

    @Override
    @InitBinder()
    public void initBinder(WebDataBinder binder) {
        super.setBaseService(hospitalService);
    }

    /**
     * 根据医院名称查询医院列表信息 effective_time
     * @param hosName
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据医院名称查询医院列表信息")
    @GetMapping("/selectListByHosName")
    @ResponseBody
    public HttpResult selectListByHosName(@RequestParam String hosName) throws Exception {
        return HttpResult.success(hospitalService.selectListByHosName(hosName));
    }

    /**
     * 查询所有未注销的医院信息列表
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询所有未注销的医院信息列表")
    @GetMapping("/selectListByStatus")
    @ResponseBody
    public HttpResult selectListByStatus() throws Exception {
        String status="0";
        return HttpResult.success(hospitalService.selectListByStatus(status));
    }

    @ApiOperation(value = "H5页面获取医院信息")
    @PostMapping("/selectListByH")
    @ResponseBody
    public HttpResult selectListByH() throws Exception {
        return HttpResult.success();
    }


    /**
     * 上传医生信息到预约挂号平台
     * @url /pub/staff_hosptal/upload
     * @return
     */
    @PostMapping("/upload")
    @ResponseBody
    public HttpResult hospitalUpload(@RequestParam Long hospitalId) throws Exception {
        hospitalService.upload(hospitalId);
        return HttpResult.success("上传医生信息到预约挂号平台！");
    }

    /**
     * 上传医生信息到预约挂号平台
     * @url /pub/pubHospital/jkt_upload
     * @return
     */
    @PostMapping("/jktUpload")
    @ResponseBody
    public HttpResult jktUpload(Long hospitalId) throws Exception {
        hospitalService.jktUpload(hospitalId);
        return HttpResult.success("上传医院信息到健康通预约挂号平台成功！");
    }

    @ApiOperation(value = "健康通--添加预约")
    @PostMapping("/regPoint")
    @ResponseBody
    public JktOutParameter regPoint(@RequestBody JktRegPointInParameter inParameter) throws Exception {
        log.info("regPoint: "+inParameter);
        System.out.println("regPoint: "+inParameter);
        String  DecryptedinParameter= AESUtils.aesDecrypt(inParameter.getBizContent(),"jfdjk670qEH5lm3b");
        log.info("regPoint: "+DecryptedinParameter);
        System.out.println("解密后："+DecryptedinParameter);
        JktRegPoint record = JSONUtil.toBean(DecryptedinParameter,JktRegPoint.class);
        JktOutParameter outParameter = new JktOutParameter();
        JktRegPointOutParameter jktRegPointOutParameter = new JktRegPointOutParameter();
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("patIdentityNum",record.getPapersNo());
        List<PubSufferer> sufferers = suffererService.selectList(paramMap);
        PubSufferer pubSufferer = new PubSufferer();
        if (CollectionUtils.isEmpty(sufferers)){
            paramMap.put("patPhone",record.getPhoneNo());
            paramMap.put("patIdentityNum",record.getPapersNo());
            List<PubPatients> patientsList = pubPatientsService.selectList(paramMap);
            if(CollectionUtils.isEmpty(patientsList)){
                PubPatients pubPatients = new PubPatients();
                pubPatients.setPatName(record.getPatientName());
                pubPatients.setPatIdentityNum(record.getPapersNo());
                if (IdcardUtil.isValidCard(pubPatients.getPatIdentityNum())){
                    pubPatients.setPatSex(IdcardUtil.getGenderByIdCard(pubPatients.getPatIdentityNum()));
                }
                pubPatients.setPatPhone(record.getPhoneNo());
                pubPatients.setPassword(record.getPhoneNo());
                pubPatientsService.insert(pubPatients);
                pubSufferer = new PubSufferer();
                pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                pubSufferer.setPatId(pubPatients.getId());
                pubSufferer.setPatName(pubPatients.getPatName());
                pubSufferer.setPatSex(pubPatients.getPatSex());
                pubSufferer.setPatPhone(pubPatients.getPatPhone());
                suffererService.insert(pubSufferer);
            }else {
                PubPatients pubPatients = patientsList.get(0);
                pubSufferer = new PubSufferer();
                pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                pubSufferer.setPatId(pubPatients.getId());
                pubSufferer.setPatName(record.getPatientName());
                pubSufferer.setPatSex(pubPatients.getPatSex());
                pubSufferer.setPatPhone(pubPatients.getPatPhone());
                suffererService.insert(pubSufferer);
            }
        }else {
            List<PubSufferer> suffererList = sufferers.stream().filter(sufferer -> sufferer.getPatName().equals(record.getPatientName())&& sufferer.getPatPhone().equals(record.getPhoneNo())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(suffererList)){
                PubPatients pubPatients = new PubPatients();
                pubPatients.setPatName(record.getPatientName());
                pubPatients.setPatIdentityNum(record.getPapersNo());
                if (IdcardUtil.isValidCard(pubPatients.getPatIdentityNum())){
                    pubPatients.setPatSex(IdcardUtil.getGenderByIdCard(pubSufferer.getPatIdentityNum()));
                }
                pubPatients.setPatPhone(record.getPhoneNo());
                pubPatients.setPassword(record.getPhoneNo());
                pubPatientsService.insert(pubPatients);
                pubSufferer = new PubSufferer();
                pubSufferer.setPatIdentityNum(pubPatients.getPatIdentityNum());
                pubSufferer.setPatId(pubPatients.getId());
                pubSufferer.setPatName(pubPatients.getPatName());
                pubSufferer.setPatSex(pubPatients.getPatSex());
                pubSufferer.setPatPhone(pubPatients.getPatPhone());
                suffererService.insert(pubSufferer);
            }else {
                pubSufferer = suffererList.get(0);
            }
        }
        OrdAppointment appointment = new OrdAppointment();
        appointment.setPatId(pubSufferer.getId());
        appointment.setSufferId(pubSufferer.getPatId());
        appointment.setPatName(pubSufferer.getPatName());
        if (Optional.ofNullable(pubSufferer.getPatSex()).isPresent()){
            appointment.setPatSex(pubSufferer.getPatSex().toString());
        }else {
            appointment.setPatSex("9");
        }
        appointment.setPhone(pubSufferer.getPatPhone());
        OrdSourceDetail sourceDetail = sourceDetailService.selectByPrimaryKey(record.getPointId());
        if (!Optional.ofNullable(sourceDetail).isPresent()){
            outParameter.setSuccess(0);
            outParameter.setRespCode("500");
            outParameter.setRespDesc("未找到有效的排班！");
            /*outParameter.setValue(JSONUtil.parse(AESUtils.aesEncrypt(jktRegPointOutParameter,"jfdjk670qEH5lm3b")));*/
            outParameter.setValue(AESUtils.aesEncrypt(jktRegPointOutParameter,"jfdjk670qEH5lm3b"));
            return outParameter;
        }
        appointment.setSerialNumber(sourceDetail.getSerialNumber());
        appointment.setPatIdentityNum(pubSufferer.getPatIdentityNum());
        appointment.setBinId(sourceDetail.getBinId());
        appointment.setBinName(sourceDetail.getBinName());
        appointment.setDepId(sourceDetail.getDepId());
        appointment.setDepName(sourceDetail.getDepName());
        appointment.setDoctorId(sourceDetail.getDoctorId());
        appointment.setDoctorName(sourceDetail.getDoctorName());
        appointment.setSchedulingId(sourceDetail.getSchedulingId());
        appointment.setSourceDetailId(sourceDetail.getId());
        appointment.setHospitalId(sourceDetail.getHospitalId());
        appointment.setVisitTime(sourceDetail.getVisitTime());
        appointment.setVisitDate(sourceDetail.getSchedulingDate());
        appointment.setTimeState(sourceDetail.getTimeState());
        appointment.setAppId(record.getOrderId());
        appointment.setSpNo("jkt");
        appointment.setSpName("jkt");
        appointment.setAppStatus(0);
        appointment.setAppType("0");
        String result ="";

        try {
            System.out.println(isJktAppointment(appointment));
            result = ordAppointmentService.createByBack(appointment);
            jktRegPointOutParameter.setOrderId(record.getOrderId().toString());
            jktRegPointOutParameter.setHospId(record.getHospId());
            jktRegPointOutParameter.setDeptId(record.getDeptId().toString());
            jktRegPointOutParameter.setDoctorId(record.getDoctorId().toString());
            jktRegPointOutParameter.setScheduleId(record.getScheduleId().toString());
            jktRegPointOutParameter.setPointId(record.getPointId().toString());
            outParameter.setSuccess(1);
            outParameter.setRespCode("");
            outParameter.setRespDesc(result);
            jktRegPointOutParameter.setRegId(appointment.getId().toString());
            jktRegPointOutParameter.setRegPassword(appointment.getPassword());
            outParameter.setValue(AESUtils.aesEncrypt(jktRegPointOutParameter,"jfdjk670qEH5lm3b"));
            log.info(outParameter.getValue().toString());
        }catch (Exception e){
            outParameter.setSuccess(0);
            outParameter.setRespCode("500");
            outParameter.setRespDesc(e.getMessage());
            outParameter.setValue(AESUtils.aesEncrypt(jktRegPointOutParameter,"jfdjk670qEH5lm3b"));
        }finally {
            System.out.println(JSONUtil.parseObj(outParameter).toStringPretty());
            return outParameter;
        }
    }

    @ApiOperation(value = "健康通-取消预约")
    @PostMapping("/cancelReg")
    @ResponseBody
    public JktOutParameter cancelReg(@RequestBody JktCancelRegInParameter inParameter) throws Exception {
        String  DecryptedinParameter= AESUtils.aesDecrypt(inParameter.getBizContent(),"jfdjk670qEH5lm3b");
        log.info("cancelReg: "+inParameter);
        System.out.println("cancelReg: "+inParameter);
        JktCancelReg record = JSONUtil.toBean(DecryptedinParameter,JktCancelReg.class);
        JktOutParameter outParameter = new JktOutParameter();
        OrdAppointment appointment = ordAppointmentService.selectByPrimaryKey(record.getRegId());
        appointment.setSpName("jkt");
        try {
            outParameter.setSuccess(1);
            outParameter.setRespCode("200");
            outParameter.setRespDesc(ordAppointmentService.cancelByBack(appointment));
        }catch (Exception e){
            outParameter.setSuccess(0);
            outParameter.setRespCode("500");
            outParameter.setRespDesc(e.getMessage());
        }finally {
            System.out.println(outParameter);
            return outParameter;
        }
    }

    /**
     * 同一个患者同一个医生只能预约一个号子
     * @param record
     * @return
     */
    private String isJktAppointment(OrdAppointment record) throws Exception {
        log.info(String.valueOf(record));
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("sourceDetailId",record.getSourceDetailId());
        paramMap.put("appStatus","0");
        List<OrdAppointment> appointmentList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentList)){
            throw new Exception("此号已被预约 请选择其他号源！");
        }
        paramMap.clear();
        paramMap.put("schedulingId",record.getSchedulingId());
        paramMap.put("patId",record.getPatId());
        paramMap.put("appStatus","0");
        //同一个患者同一个排班下 只能预约一个号子
        List<OrdAppointment> appointmentTList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentTList)){
            OrdAppointment ordAppointment = appointmentTList.get(0);
            throw new Exception("您已经预约"
                    +ordAppointment.getDepName()
                    +ordAppointment.getDoctorName()
                    + LocalDateTimeUtil.format(ordAppointment.getVisitDate(), DatePattern.CHINESE_DATE_PATTERN)
                    +ordAppointment.getVisitTime()+",第"+ordAppointment.getSerialNumber()+"号，请勿重复预约");
        }
        paramMap.clear();
        paramMap.put("schedulingId",record.getSchedulingId());
        paramMap.put("patIdentityNum",record.getPatIdentityNum());
        paramMap.put("appStatus","0");
        //同一个患者同一个排班下 只能预约一个号子
        List<OrdAppointment> appointmentWList = ordAppointmentService.selectList(paramMap);
        if (!CollectionUtils.isEmpty(appointmentWList)){
            OrdAppointment ordAppointment = appointmentWList.get(0);
            throw new Exception(record.getPatName()+"您好！您已经预约"
                    +ordAppointment.getDepName()
                    +ordAppointment.getDoctorName()
                    +LocalDateTimeUtil.format(ordAppointment.getVisitDate(),DatePattern.CHINESE_DATE_PATTERN)
                    +ordAppointment.getVisitTime()+",第"+ordAppointment.getSerialNumber()+"号，请勿重复预约");
        }
        return "";
    }
}
